package com.sky.chapter2.Unsafe;

/**
 * description: 指令重排序
 * Author by cqb, Date on 2020/10/2，14:47
 */
public class InstructionReordering {
    private static int num = 0;
    //    private volatile static boolean ready=false;
    private static boolean ready = false;


    public static class ReadThread extends Thread {

        @Override
        public void run() {
            while (!Thread.currentThread().isInterrupted()) {
                if (ready) {                                        //step:1
                    System.out.println(num + num);                   //step:2
                }
                System.out.println("read thread...");
            }
        }
    }

    public static class WriteThread extends Thread {
        @Override
        public void run() {
            num = 2;                                                          //step:3
            // System.out.println(num);
            ready = true;                                                   //step:4
            System.out.println("writeThread set over...");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ReadThread read = new ReadThread();
        read.start();
        WriteThread write = new WriteThread();
        write.start();


        Thread.sleep(1);

        read.interrupt();
        System.out.println("main exit");
    }
}
